<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId"  @change="deptChange1" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="停车场">
          <el-select v-model="listQuery.parkId" @change="parkChange" clearable placeholder="请选择" style="width: 180px;">
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label=" 长租类型  " prop="staticRuleId">
          <el-select v-model="listQuery.staticRuleId" clearable placeholder="请选择">
            <el-option
              v-for="item in ruleList1"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="车牌号码">
          <el-input v-model="listQuery.plateNumber" clearable class="filter-item" style="width: 180px;" placeholder="请输入"/>
        </el-form-item>

        <el-form-item label="车位号">
          <el-input v-model="listQuery.parkingSpaceNumber" clearable class="filter-item" style="width: 180px;" placeholder="请输入"/>
        </el-form-item>

        <el-form-item label="车主姓名">
          <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 180px;" placeholder="请输入"/>
        </el-form-item>

        <el-form-item label="车主电话">
          <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 180px;" placeholder="请输入"/>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="listQuery.status" clearable placeholder="请选择" style="width: 180px;">
            <el-option
              v-for="item in statusTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否删除">
          <el-select v-model="listQuery.deleteFlag" clearable placeholder="请选择" style="width: 180px;">
            <el-option
              v-for="item in dict.type.EYesOrNo"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button
          v-hasPermi="['admin:parkInside:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >
      <el-table-column align="center" label="机构名称" prop="departmentName" />
      <el-table-column align="center" label="车牌号" prop="plateNumber"/>

      <el-table-column align="center" label="车位号" prop="parkingSpaceNumber"/>

      <el-table-column align="center" label="车主姓名" prop="name"/>

      <el-table-column align="center" label="车主电话" prop="mobile"/>

      <el-table-column align="center" label="车场名称" prop="parkName"/>

      <el-table-column align="center" label="长租类型" prop="ruleStr"/>
      <el-table-column align="center" label="购买类型" prop="buyTypeStr"/>
      <el-table-column align="center" label="金额" prop="payedMoney"/>

      <el-table-column align="center" label="生效时间" prop="startTime"/>
      <el-table-column align="center" label="到期时间" prop="endTime"/>

      <el-table-column align="center" label="状态" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.EParkInsideStatus" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column align="center" label="备注" prop="remark" width="140" show-overflow-tooltip />

      <el-table-column align="center" label="操作" width="220" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            v-hasPermi="['admin:parkInside:update']"
            type="text"
            size="small"
            v-if="row.deleteFlag==0"
            @click="startEditInside(row)">编辑</el-button>
          <el-button
            v-hasPermi="['admin:parkInside:continueRent']"
            type="text"
            size="small"
            v-if="(row.status == 1 || row.status == 3) && row.deleteFlag==0"
            @click="startContinueRent(row)">续租</el-button>
          <el-dropdown size="mini" v-if="(row.status == 1 || row.status == 2 )" @command="(command) => handleCommand(command, row)"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="startCancelRent" v-if="row.status == 1 && row.deleteFlag==0" v-hasPermi="['admin:parkInside:cancelRent']"
              >退租
              </el-dropdown-item>
              <el-dropdown-item command="handleDelete" v-if="row.status == 2 && row.deleteFlag==0" v-hasPermi="['admin:parkInside:logicDelete']"
              >删除
              </el-dropdown-item>
              <el-dropdown-item command="operationLog" v-hasPermi="['admin:parkInside:listOperationLog']"
              >操作日志
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogType == 1?'添加固定车':'修改固定车'" :visible.sync="dialogFormVisible" width="45%">
      <el-form ref="dialogForm"  :rules="formRules" :model="dialogForm"  label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label=" 机构  " prop="departmentId">
              <el-select style="width: 100%;" v-model="dialogForm.departmentId" :disabled="dialogType == 2"
              placeholder="请选择" @change="deptChange">
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 停车场  " prop="parkId">
              <el-select style="width: 100%;" v-model="dialogForm.parkId" :disabled="dialogType == 2" placeholder="请选择" @change="selectParkId">
                <el-option
                  v-for="item in parkList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label=" 车牌号  " prop="plateNumber">
              <div class="" style="width: 100%;">
                <el-input v-model="dialogForm.plateNumber" clearable class="filter-item" placeholder=""/>
                <div style="color:red;">*(用英文逗号,间隔多个车牌号，末尾不可逗号结尾，例如闽xyz111,闽xyz222)</div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="车位号 " prop="parkingSpaceNumber">
          <div class="" style="width: 100%;">
            <el-input v-model="dialogForm.parkingSpaceNumber" clearable class="filter-item" placeholder=""/>
            <div style="color:red;">*(用英文逗号,间隔多个车位号，末尾不可逗号结尾，例如闽011,022)</div>
          </div>
        </el-form-item>
        <el-form-item label=" 车主姓名  " prop="name">
          <el-input v-model="dialogForm.name" clearable class="filter-item" placeholder=""/>
        </el-form-item>
        <el-form-item label=" 车主电话  " prop="mobile">
          <el-input v-model="dialogForm.mobile" clearable class="filter-item" placeholder=""/>
        </el-form-item>
        <el-form-item label=" 备注  ">
          <el-input v-model="dialogForm.remark" clearable class="filter-item" placeholder=""/>
        </el-form-item>
        <el-form-item v-if="dialogType != 1" label=" 生效时间  " prop="dateRange">
          <el-date-picker
            v-model="dialogForm.dateRange"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :clearable="false"
            :default-time="['00:00:00','00:00:00']"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label=" 长租类型  " prop="ruleId">
          <el-select style="width: 100%;" v-model="dialogForm.ruleId" placeholder="请选择">
            <el-option
              v-for="item in ruleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogType == 1" label=" 数量  " prop="quantity">
          <el-input v-model="dialogForm.quantity" clearable class="filter-item"  placeholder=""/>
        </el-form-item>
        <el-form-item label="车位数" prop="spaceCount">
          <el-input-number v-model="dialogForm.spaceCount" step-strictly :step="1" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="多辆车入场选项" prop="multiCarEnterOption">
          <el-select style="width: 100%;" v-model="dialogForm.multiCarEnterOption" placeholder="请选择多辆车入场选项">
            <el-option
              v-for="item in dict.type.EParkInsideMultiCarEnterOption"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"/>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="continueRentDialogVisible" title="固定车续租" width="28%">
      <el-form :inline="true" align="center">
        <!-- <el-form-item label="* 车牌号  ">
          <el-input v-model="dialogForm.plateNumber" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
        <el-form-item label="* 车主姓名  ">
          <el-input v-model="dialogForm.name" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
        <el-form-item label="* 车主电话  ">
          <el-input v-model="dialogForm.mobile" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item> -->
        <el-form-item label="* 长租类型  ">
          <el-select v-model="dialogForm.ruleId" disabled placeholder="请选择">
            <el-option
              v-for="item in ruleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="* 数量  ">
          <el-input v-model="dialogForm.quantity" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmContinueRent()">确定</el-button>
        <el-button @click="continueRentDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="cancelRentDialogVisible" :title="dialogTitle" width="50%">
      <div v-if="dialogTitle == '操作日志'">
        <div>
          <el-form :inline="true">
            <el-form-item label="时间选择" prop="dateRange">
              <el-date-picker
                v-model="logListQuery.dateRange"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width:333px;"
                :default-time="['00:00:00','23:59:59']"
              ></el-date-picker>
            </el-form-item>

            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="logHandleFilter">查找</el-button>
          </el-form>
        </div>

        <!-- 查询结果 -->
        <el-table v-loading="logListLoading" :data="logList" element-loading-text="正在查询中。。。" border fit highlight-current-row >
          <el-table-column align="center" label="操作内容" prop="content" show-overflow-tooltip/>
          <el-table-column align="center" label="操作人员" prop="createBy" width="100" show-overflow-tooltip/>
          <el-table-column align="center" label="操作时间" prop="createTime" width="200" show-overflow-tooltip/>
        </el-table>
        <pagination
        v-show="logTotal>0"
        :total="logTotal"
        :page.sync="logListQuery.page"
        :limit.sync="logListQuery.pageSize"
        @pagination="operationLog" />
      </div>
      <div v-else>
        <el-form >
          <el-row>
            <el-col :span="12">
              <el-form-item label="* 车牌号  ">
                <el-input v-model="dialogForm.plateNumber" disabled class="filter-item" style="max-width: 260px;" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="* 车主姓名  ">
                <el-input v-model="dialogForm.name" disabled class="filter-item" style="max-width: 260px;" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="* 车主电话  ">
                <el-input v-model="dialogForm.mobile" disabled class="filter-item" style="max-width: 260px;" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="* 剩余天数  ">
                <el-input v-model="cancelRentForm.leftDays" disabled class="filter-item" style="max-width: 260px;" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="* 退款金额  ">
                <el-input v-model="cancelRentForm.backMoney" disabled class="filter-item" style="max-width: 260px;" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" align="right">
        <el-button v-if="dialogTitle != '操作日志'" @click="confirmCancelRent()">确定</el-button>
        <el-button @click="cancelRentDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
/* eslint-disable eqeqeq */

import { fetchList, createParkInside, updateParkInside, parkInsideContinueRent, parkInsideCancelRentInfo,
parkInsideCancelRent,logicDelete,parkInsideDetail,operationLogList } from '@/api/parkInside'
import { selectAvailables } from '@/api/parkStaticRule'
import { getDepartmentList,getListAuthPark } from '@/api/base'
import { getData, } from '@/api/system/dictionary'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { validateMobile } from '@/utils/validate'
export default {
  name: 'ParkInside',
  dicts: ['EParkInsideStatus','EYesOrNo','EParkInsideMultiCarEnterOption'],
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      statusTypeList: [],
      listQuery: {
        page: 1,
        pageSize: 20,
        deleteFlag:'0'
      },
      downloadLoading: false,
      dialogTitle: '退租',
      dialogFormVisible: false,
      continueRentDialogVisible: false,
      cancelRentDialogVisible: false,
      delDialogFormVisible: false,
      dialogForm: {},
      cancelRentForm: {},
      dialogType: 1,
      name: '',
      deleteInsideId: 0,
      departmentList: [],
      parkList: [],
      allParkList: [],
      ruleList: [],
      ruleList1: [],
      formRules: {
        parkId: [{ required: true, message: '请选择停车场', validator: this.checkSelected, trigger: 'change' }],
        plateNumber: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入车主姓名', trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入车主电话', trigger: 'blur' },
          { validator: validateMobile.bind(this), trigger: 'blur' },
        ],
        ruleId: [{ required: true, message: '请选择长租类型', validator: this.checkSelected, trigger: 'change' }],
        quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择机构名称', validator: this.checkSelected, trigger: 'change' }],
        dateRange: [{ required: true, message: '请选择生效时间', validator: this.checkSelected, trigger: 'change' }],
        spaceCount: [{ required: true, message: '请输入车位数', trigger: 'blur' }],
        multiCarEnterOption: [{ required: true, message: '请选择多辆车入场选项', validator: this.checkSelected, trigger: 'change' }],
      },
      logListQuery: {
        page: 1,
        pageSize: 10,
        dateRange:[],
      },
      logList: null,
      logTotal: 0,
      logListLoading: true,
    }
  },
  created() {
    this.getDepartmentList()

		this.getData()
  },
  methods: {
    async parkInsideDetail(id){//详情
      let res = await parkInsideDetail(id)
      let data = res.data || {}
      return data
    },
    // 更多操作触发
    handleCommand(command, row) {
      this.form = {...row}
      switch (command) {
        case "startCancelRent":
          this.dialogTitle = '退租'
          this.startCancelRent(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "operationLog":
          this.dialogTitle = '操作日志'
          this.logListQuery.parkInsideId = row.id
          this.cancelRentDialogVisible = true
          this.operationLog();
        break;
      }
    },
    async operationLog(){//操作日志
      this.logListLoading = true
      let dateRange = this.logListQuery.dateRange || []
      let logListQuery = {...this.logListQuery}
      if(dateRange.length) {
        logListQuery.startTime = dateRange[0]
        logListQuery.endTime = dateRange[1]
      }
      delete logListQuery.dateRange
      let response = await operationLogList(logListQuery)
      let data  = response.data || {}
      this.logList = data.list || []
      this.logTotal = data.total || 0
      this.logListLoading = false
    },
    handleDelete(row){//删除
      this.$confirm(`您确定删除该数据`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        logicDelete({ id: row.id }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    getDepartmentList(){//获取机构
      getDepartmentList().then(async res => {
        this.departmentList = res.data || []
        if(this.departmentList.length == 1) {
          let departmentId = this.departmentList[0].id
          this.allParkList = await this.getListAuthPark(departmentId)
          let listQuery = {...this.listQuery}
          if(this.allParkList.length) {
            let parkId = this.allParkList[0].id
            listQuery.parkId = parkId
            var getStatisRules = { 'parkId': parkId, 'page': 1 }
            let response = await selectAvailables(getStatisRules)
            this.ruleList1 = response.data || []
            if(this.ruleList1.length) listQuery.staticRuleId = this.ruleList1[0].id
          }
          listQuery.departmentId = departmentId
          this.listQuery = {...listQuery}
        }
        this.getList()
      })
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({departmentId})
      return res.data || []
    },
		async getData(){//状态
			let res = await getData('EParkInsideStatus')
			let list = res.data || []
			this.statusTypeList = [...list]
		},
    async deptChange1(e){//机构下拉选择
      let listQuery = {...this.listQuery}
      listQuery.parkId = ''
      listQuery.staticRuleId = ''
      this.listQuery = {...listQuery}
      this.ruleList1 = []
      if(!e) return this.allParkList = []
      this.allParkList = await this.getListAuthPark(e)
    },
    async parkChange(event){
      this.ruleList1 = []
      var getStatisRules = { 'parkId': event, 'page': 1 }
      let listQuery = {...this.listQuery}
      listQuery.staticRuleId = ''
      this.listQuery = {...listQuery}
      if(!event) return this.ruleList1 = []
      selectAvailables(getStatisRules).then(response => {
        this.ruleList1 = response.data || []
      })
    },
    // 校验下拉框
    checkSelected(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },

    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data  = response.data || {}
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    logHandleFilter(){//日志查询
      this.logListQuery.page = 1
      this.operationLog()
    },
    getStatus(status) {
      let result = '未知'
      for (let i = 0; i < this.statusTypeList.length; i++) {
        if (this.statusTypeList[i].id == status) {
          result = this.statusTypeList[i].name
          break
        }
      }
      return result
    },

    startAdd() {
      this.dialogForm = {
        dateRange:[]
      }
      this.dialogFormVisible = true
      this.dialogType = 1
      this.parkList = []
      this.ruleList = []
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
      this.getDepartmentList()
    },
    geshihuadh(str){//格式化逗号格式车牌和车位号
      let plateNumber = this.dialogForm[str] || ''
      plateNumber = plateNumber.replace(/\s+/g, '');
      let plateNumbers = plateNumber.replace(/，/g, ',');
      let chepaiList = plateNumbers.split(',')
      chepaiList = chepaiList.filter(item=>item)
      let zuihou = chepaiList.toString()
      return zuihou
    },
    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let dialogForm = {...this.dialogForm}
          dialogForm.startTime = this.dialogForm.dateRange[0]
          dialogForm.endTime = this.dialogForm.dateRange[1]

          dialogForm.plateNumber = this.geshihuadh('plateNumber')
          dialogForm.parkingSpaceNumber = this.geshihuadh('parkingSpaceNumber')
          delete dialogForm.dateRange
          if (this.dialogType == 1) {
            createParkInside(dialogForm).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            updateParkInside(dialogForm).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          }
        }
      })
    },
    confirmContinueRent() {
      parkInsideContinueRent(this.dialogForm).then(response => {
        this.$message({
          message: '续租成功!',
          type: 'success'
        })
        this.getList()
        this.continueRentDialogVisible = false
        this.dialogForm = {}
      })
    },
    confirmCancelRent() {
      parkInsideCancelRent(this.dialogForm).then(response => {
        this.$message({
          message: '退租成功!',
          type: 'success'
        })
        this.getList()
        this.cancelRentDialogVisible = false
        this.dialogForm = {}
      })
    },
    async startEditInside(row) {
      this.dialogFormVisible = true
      this.dialogType = 2
      let data = await this.parkInsideDetail(row.id)
      this.dialogForm = {...data,dateRange:data.startTime && data.endTime ? [data.startTime,data.endTime] : []}
      this.parkList = []
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
      this.parkList = await this.getListAuthPark(this.dialogForm.departmentId)
      this.getDepartmentList()
      this.selectParkId(row.parkId)
    },
    startContinueRent(row) {
      this.continueRentDialogVisible = true
      this.dialogForm = { ...row }
      this.selectParkId(row.parkId)
    },
    startCancelRent(row) {
      this.dialogForm = {...row}
      parkInsideCancelRentInfo(this.dialogForm).then(response => {
        this.cancelRentForm = response.data || {}
        this.cancelRentDialogVisible = true
      })
    },
    deptChange(event){
      let dialogForm = {...this.dialogForm}
      dialogForm.parkId = ''
      this.dialogForm = {...dialogForm}
      this.selectDepartmentId(event)
    },
    async selectDepartmentId(event) {
      this.parkList = []
      this.parkList = await this.getListAuthPark(event)
    },
    async selectAvailables(event){
      var getStatisRules = { 'parkId': event, 'page': 1 }
      let response = await selectAvailables(getStatisRules)
      this.ruleList = response.data || []
    },
    selectParkId(event) {
      this.ruleList = []
      this.selectAvailables(event)
    }
  }
}
</script>
